#!/usr/bin/php
<?php 
require("/http/matchtest/classes/class.phpmailer.php");

$currenttime = time();
$readabledate = date("D, M j H:i:s",$currenttime);
$filedate = date("YmdHis",$currenttime);

error_reporting(E_ERROR | E_PARSE);

if(isset($argv[1])){
    $debug = TRUE;
} else {
    unset($debug);
}

if (isset($debug)) { echo "\n* * * * *  D E B U G = O N * * * * *\n";}
if (isset($debug)) { echo "\nContents of testresults.txt file\n";}
if (isset($debug)) { echo file_get_contents('/http/matchtest/testresults.txt')."\n";}

// read in the testresults.txt file
$lines = file('/http/matchtest/testresults.txt');
$numitems = count($lines);
if (isset($debug)) { echo "Lines in testresults.txt: ".$numitems."\n";}
$pieces = explode("|",$lines[0]);
if (isset($debug)) { echo "Previous Datestamp: ".trim($pieces[0])."\n";}
if (isset($debug)) { echo "Previous Version: ".trim($pieces[1])."\n";}

$output = MakeAdCall('http://crtldev.aimatch.com:60000/canary/hserver');
$output_array = MakeOutputArray($output,$debug);
$version = TraceInfo($output_array,"Server",$debug);

if (isset($debug)) { echo "New Version: ".$version."\n";}

$lines[0] = $currenttime."|".trim($version)."\n";
$fp=fopen("/http/matchtest/testresults.txt","w+");
foreach($lines as $key => $value){
	fwrite($fp,$value); }
fclose($fp);

if (isset($debug)) { echo "\nContents of testresults.txt file\n";}
if (isset($debug)) { echo file_get_contents('/http/matchtest/testresults.txt')."\n";}


// read in the tests to run from the ./tests directory.
// any file starting with "test_" will be executed.
if ($handle = opendir('/http/matchtest/tests')) {
    if (isset($debug)) { echo "Directory handle: $handle\n"; }
    if (isset($debug)) { echo "Files:\n"; }
$i=0;

    while (false !== ($file = readdir($handle))) {
        if(stristr($file,"test_")){
			if (isset($debug)) { echo "$file\n"; }
			$test_files[$i] = $file;
			$i++;
		}
    }
    closedir($handle);
	$num_tests = $i--;
}
if (isset($debug)) { echo "Number of Test Files: ".$num_tests."\n"; }
if (isset($debug)) { echo print_r($test_files); echo "\n";}

$i=0;
while($i < $num_tests){
	$commandline = "/usr/bin/php /http/matchtest/tests/".$test_files[$i]." commandline";
	if (isset($debug)) { echo $commandline."\n"; }
	shell_exec($commandline);
	sleep(1);
	$i++;
}
// need a seperate test to run the companion ad script multiple times.
if (isset($debug)) { echo "Running Companion Ad Test: /http/matchtest/runcompanion.sh\n"; }
   shell_exec("/http/matchtest/runcompanion.sh");
	
$lines = file('/http/matchtest/testresults.txt');
// Loop through the testresults.txt file and re-run any tests that fail (Except for the Companion Ad test)
// The Companion Ad Test is not re-run because it is an multiple run test and one request may give false results.
foreach ($lines as $line_num => $line) {
	$pieces = explode ("|",$line);
	if($pieces[0] == "fail"){
		if($pieces[3] != "test_companion.php"){
			echo "\n".$pieces[1]." ".$pieces[0]."ed. Rerunning ".$pieces[3]."\n";
			$rerun_commandline = "/usr/bin/php /http/matchtest/tests/".$pieces[3]." commandline";
			if (isset($debug)) { echo $rerun_commandline."\n"; }
			shell_exec($rerun_commandline);
			$reruntesttext = "";
		}
	}
}

// check that all the tests have run and have written their results out to the testresults.txt file
// if the file is not formatted properly (zero bytes) re-write the file out and then set an error flag.
$filesize = filesize("/http/matchtest/testresults.txt");
if (isset($debug)) { echo "Testresults.txt Filesize: ".$filesize."\n"; }
//$filesize = 10;

if($filesize < 100){
	if (isset($debug)) { echo "Filesize Error\n"; }
	if (isset($debug)) { echo "Restore the old file\n"; }
		$fp=fopen("/http/matchtest/testresults.txt","w+");
		foreach($lines as $key => $value){
			if (isset($debug)) { echo "Old Value: ".$value."\n"; }	
// Because of the failure, change all the test results to FAIL and write out the new file.
			$newvalue = str_replace("pass|", "fail|", $value);
			if (isset($debug)) { echo "New Value: ".$newvalue."\n"; }	
			fwrite($fp,$newvalue); }
		fclose($fp);
	if (isset($debug)) { echo "\nContents of testresults.txt file\n";}
	if (isset($debug)) { echo file_get_contents('/http/matchtest/testresults.txt')."\n";}

	if (isset($debug)) { echo "Send failure message.\n"; }
	sendClusterFailureEmail($readabledate);
}
else {
	if (isset($debug)) { echo "Filesize OK\n"; }
	if (isset($debug)) { echo "Backup the testresults.txt file\n"; }
		$fp=fopen("/http/matchtest/testresults.bak","w+");
		foreach($lines as $key => $value){
			fwrite($fp,$value); }
		fclose($fp);
	if (isset($debug)) { echo "\nContents of testresults.txt file\n";}
	if (isset($debug)) { echo file_get_contents('/http/matchtest/testresults.txt')."\n";}

		if (isset($debug)) { echo "Regular success or failure email\n"; }
	sendTestResultsEmail($readabledate);
}

// Delete archived files over 30 days old.
$delete_files_command = "find /http/matchtest/archived_results -mtime +30 -exec rm {} \;";
shell_exec($delete_files_command);
	

// Send out the status email.
function sendClusterFailureEmail($readabledate){
	    $mail = new phpmailer();

        $mail->IsSendmail();                                      // set mailer to use SMTP
        $mail->Host = "smtp.gmail.com";       
        $mail->From = "scriptserver@aimatch.com";
        $mail->FromName = "Canary Testing";
        $mail->SMTPAuth = "true";
        $mail->Username = "aimatchrobc@gmail.com";
        $mail->Password = "@1m@tchr0bc";
        $mail->AddAddress("rob@aimatch.com");
        $mail->AddAddress("dev@aimatch.com");
        $mail->AddAddress("steved@aimatch.com");
        $mail->AddReplyTo("rob@aimatch.com", "Robert Cox");

        $mail->WordWrap = 65;                                 // set word wrap to 65 characters
        $mail->IsHTML(true);                                  // set email format to HTML

        
        $mail->Subject = "CANARY: Canary Testing FAILED on ".$readabledate;
        $mail->Body    = "The Canary Cluster was not available and could not be tested.";

        if(!$mail->Send())
        {
            echo "Message could not be sent. <p>";
            echo "Mailer Error: " . $mail->ErrorInfo;
            exit;
         }


}

function sendTestResultsEmail($readabledate){
$filedate = date("YmdHis",$currenttime);

// create the error.txt file on the server
$lines = file('/http/matchtest/testresults.txt');
$numitems = count($lines);

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
	$pieces = explode("|",$line);
//	print_r($pieces);
	if($line_num == 0){ 
		$datestamp = trim($pieces[0]); 
		$version = trim($pieces[1]); }
	else {
		$status[$line_num] = $pieces[0];
		$testname[$line_num] = $pieces[1];
		$testdesc[$line_num] = $pieces[2];
		$testurl[$line_num] = $pieces[3];
		$testtime[$line_num] = trim($pieces[4]);
    	if (isset($debug)) { echo "Line #<b>{$line_num}</b> Status: " . $status[$line_num] . "<br />\n"; }
    	if (isset($debug)) { echo "Line #<b>{$line_num}</b> Test Name: " . $testname[$line_num] . "<br />\n"; }
    	if (isset($debug)) { echo "Line #<b>{$line_num}</b> Test Description: " . $testdesc[$line_num] . "<br />\n"; }
    	if (isset($debug)) { echo "Line #<b>{$line_num}</b> Test Time: " . $testurl[$line_num] . "<br />\n"; }
    	if (isset($debug)) { echo "Line #<b>{$line_num}</b> Test Time: " . $testtime[$line_num] . "<br />\n"; }
	}
}

	$i = 1;
	$emailbody = $reruntesttext;
	$emailbody = $emailbody."<font face=\"Tahoma\" size=\"2\">\n";
	$emailbody = $emailbody."<table class=\"record-list\">\n";
	$emailbody = $emailbody."<thead>\n";
    $emailbody = $emailbody."<tr>\n";
    $emailbody = $emailbody."<th>Status</th>\n";
    $emailbody = $emailbody."<th>Test Name</th>\n";
    $emailbody = $emailbody."<th>Description</th>\n";
    $emailbody = $emailbody."<th>Test Time</th>\n";
    $emailbody = $emailbody."<th>&nbsp;</th>\n";
    $emailbody = $emailbody."</tr>\n";
    $emailbody = $emailbody."</thead>\n";
    $emailbody = $emailbody."<tbody>\n";

	$EmailStatus = "PASSED";
	while ($i < $numitems){
		$emailbody = $emailbody."<tr>\n";
		$emailbody = $emailbody."<td>".ucfirst($status[$i])."</td>\n";
		$emailbody = $emailbody."<td><a href=\"http://tests.aimatch.com/tests/".$testurl[$i]."?web=1\" target=_blank>".$testname[$i]."</a></td>\n";
		$emailbody = $emailbody."<td>".$testdesc[$i]."</td>\n";
		$emailbody = $emailbody."<td>".date("n/j/Y g:ia",$testtime[$i])."</td>\n";
		$emailbody = $emailbody."<td class=\"action\"></td>\n";
		$emailbody = $emailbody."</tr>\n";
		if($status[$i] == "fail"){
			$EmailStatus = "FAILED";}
	$i++;
	}
    $emailbody = $emailbody."</tbody>\n";
    $emailbody = $emailbody."</table>\n";

    $emailbody = $emailbody."</font>\n";
	
	echo $emailbody;
	
	    $mail = new phpmailer();

        $mail->IsSendmail();                                      // set mailer to use SMTP
        $mail->Host = "smtp.gmail.com";       
        $mail->From = "scriptserver@aimatch.com";
        $mail->FromName = "Canary Testing";
        $mail->SMTPAuth = "true";
        $mail->Username = "aimatchrobc@gmail.com";
        $mail->Password = "@1m@tchr0bc";
        $mail->AddAddress("rob@aimatch.com");
        $mail->AddAddress("dev@aimatch.com");
        $mail->AddAddress("steved@aimatch.com");
        $mail->AddReplyTo("rob@aimatch.com", "Robert Cox");

        $mail->WordWrap = 65;                                 // set word wrap to 65 characters
        $mail->IsHTML(true);                                  // set email format to HTML

        
        $mail->Subject = "CANARY: v".$version." ".$EmailStatus." on ".$readabledate;
        $mail->Body    = $emailbody;

        if(!$mail->Send())
        {
            echo "Message could not be sent. <p>";
            echo "Mailer Error: " . $mail->ErrorInfo;
            exit;
         }

}

function MakeAdCall($url) {
	$UserAgent="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16";

    // initilize the curl call
    $ch = curl_init();
    // set useragent
    curl_setopt($ch, CURLOPT_USERAGENT, $UserAgent);
    // Set curl to use $url for http call
    curl_setopt($ch, CURLOPT_URL, $url);
    // show client headers
    curl_setopt($ch, CURLOPT_HEADER, 1);
    // have curl put X-Forwarded-For into headers
    curl_setopt($ch,CURLOPT_HTTPHEADER, $client_headers);
    // store results as the return of curl_exec
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    // Follow redirects
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);		
    // if HTML error 400 over over, fail
    curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);

    $output = curl_exec($ch);
    if (isset($debug)) { echo "\n\nHTTP Response Output:\n"; print_r($output); echo "\n\n"; }
    //close curl connection
    curl_close($ch);

return $output;
}


function MakeOutputArray($output,$debug){
        $output_array = preg_split('/[\n]/', $output, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        if (isset($debug)) { echo "\n\nHTTP Response Output (array):\n"; print_r($output_array); echo "\n\n"; }

return $output_array;
}


function TraceInfo($output_array,$string,$debug) {

        $line_match = array_values(preg_grep("/$string/", $output_array));
            if (isset($GLOBALS["debug"])) { echo "DEBUG - string:  ".$string."\n\n";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - output:  \n"; print_r($output_array); echo "\n\n";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - line_match:\n"; print_r($line_match); echo "\n\n";}
        if(stripos($line_match[0], " = ")){
			$explode = explode(" = ", $line_match[0]); }
        if(stripos($line_match[0], ":")){
			$explode_a = explode(":", trim($line_match[0]));
			if (isset($debug)) { echo "\n\nExplode A: ".$explode_a[1]."\n"; }
			$explode_b = explode(" ",trim($explode_a[1])); 
			if (isset($debug)) { echo "Explode B: ".$explode_b[0]."\n"; }
			$explode_c = explode("/",trim($explode_b[0])); 
			if (isset($debug)) { echo "Explode C: ".$explode_c[1]."\n"; }
			$result = trim($explode_c[1]); 
			if (isset($debug)) { echo "\n\nResult: ".$result."\n\n"; }
		}
        if(stripos($line_match[1], ">>>>")){
			$result = $line_match[1]; }
        if (isset($GLOBALS["debug"])) { echo "DEBUG - result:  ".$result."\n\n";}
		return $result;
}

function GetFormattedOutput($output_array, $web,$debug){
        $http_response = array_values(preg_grep("/^HTTP/", $output_array));
        $http_array = explode(" ",$http_response[0]);
        $http_return_code = trim($http_array[1]);
        $http_return_text = trim($http_array[2]);
//        if (isset($debug)) { echo "<br>DEBUG - HTTP CODE/TEXT: $http_return_code / $http_return_text<br>"; }

        /* check code = 200 or 302 and text equal OK, anything else we have an error */

        if (($http_return_text != "OK" || $http_return_code != "200")&&($http_return_text != "Relocate" || $http_return_code != "302")) {
//            if (isset($debug)) { echo "***** ALERT - HTTP CODE/TEXT: ".trim($http_response[0])." *****<br>"; }
				echo "HTTP return code/text was not 200/OK". trim($http_response[0])."<br>";
                die;
        }
		
		// count the number of elements in the response array
		$num_elements = count($output_array);
//        if (isset($debug)) { echo "The Number Of Elements in the OUTPUT Array are: ".$num_elements." <br>"; }
		
		// format the items in the array as a long concatenated string.
		$y=0;
		while($y <= $num_elements){
			$formatted_output = $formatted_output.$output_array[$y]."\n";
			$formatted_output_web = $formatted_output_web.$output_array[$y]."<br>";
			$y++;
		}
//        if (isset($debug)) { echo "The Formatted contents of OUTPUT are: ".$formatted_output_web." *****<br>"; }
		
		if($web) {
			return $formatted_output_web; }
		else {
			return $formatted_output; }
}

?>
